import { StyleSheet, Image, TouchableOpacity } from 'react-native'
import React, { useState } from 'react'
import icon_heart_empty from '@/assets/images/icon_heart_empty.png'
import icon_heart from '@/assets/images/icon_heart.png'
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  withSequence,
  withTiming
} from 'react-native-reanimated'

interface Props {
  /** 图片大小 */
  size?: number
  /** 是否选中 */
  selected: boolean
}

const HeartAnimated: React.FC<Props> = ({ size = 20, selected }) => {
  const styles = StyleSheet.create({
    icon: {
      width: size,
      height: size,
      resizeMode: 'contain'
    },
    borderView: {
      width: size,
      height: size,
      borderWidth: size / 20,
      borderColor: '#ff2242',
      position: 'absolute',
      borderRadius: size / 2
    }
  })

  const [isSelected, setIsSelected] = useState(selected)
  const scale = useSharedValue(1)
  const borderScale = useSharedValue(0)
  const opacity = useSharedValue(1)

  const onChange = () => {
    setIsSelected(!isSelected)
    // 设置图片动画值
    scale.value = withSequence(withSpring(0.7), withSpring(1))
    // 设置涟漪动画值
    scale.value = withSequence(withSpring(0.7), withSpring(1))

    if (!isSelected) {
      // 设置涟漪动画
      borderScale.value = withTiming(2, { duration: 600 })
      opacity.value = withTiming(0, { duration: 600 }, () => {
        ;(opacity.value = 1), (borderScale.value = 0)
      })
    }
  }
  const imageStyle = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }]
  }))
  const borderStyle = useAnimatedStyle(() => ({
    transform: [{ scale: borderScale.value }],
    opacity: opacity.value
  }))
  return (
    <TouchableOpacity onPress={onChange} activeOpacity={1}>
      <Animated.Image
        source={isSelected ? icon_heart : icon_heart_empty}
        style={[styles.icon, imageStyle]}
      ></Animated.Image>
      <Animated.View style={[styles.borderView, borderStyle]}></Animated.View>
    </TouchableOpacity>
  )
}

export default HeartAnimated
